package com.whf.service.impl;

import com.whf.dataobject.SellerInfo;
import com.whf.exception.SellException;
import com.whf.service.RedisLock;
import com.whf.service.SecKillService;
import com.whf.service.SellerService;
import com.whf.utils.KeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2018/7/20 0020.
 */
@Service
public class SecKillServiceImpl implements SecKillService {

    @Autowired
    private RedisLock redisLock;
    /**
     * 模拟库存10000份商品
     * 苹果手机
     * @param productId
     * @return
     */
    static Map<String,Integer> products;
    static Map<String ,Integer> stock;
    static Map<String ,String> orders;
    static{
        products=new HashMap<>();
        stock=new HashMap<>();
        orders=new HashMap<>();
        products.put("12345",10000);
        stock.put("12345",10000);
    }

    private String queryMap(String productId){
        return "活动限量"+products.get(productId)+"还剩:"+stock.get(productId)+
                "份,成功下单的用户有:"+orders.size()+"人";

    }
    @Override
    public String querySecKillProductInfo(String productId) {

        return queryMap(productId);
    }

    @Override
    public void orderProductMockDiffUser(String productId) {

        //加锁
        Long value=System.currentTimeMillis()+100;
        if(!redisLock.lock(productId, String.valueOf(value))){
           throw new SellException(101,"人太多了,抓紧重试");
        }

        //查询库存
        int stockNum=stock.get(productId);
        //如果库存为0
        if(stockNum==0){
            throw new SellException(100,"活动结束");
        }else {
            //下单,模拟不同用户下的订单
            orders.put(KeyUtil.uniqueKey(),productId);
            //减少库存
            stockNum=stockNum-1;
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //修改库存中的商品数量
            stock.put(productId,stockNum);
        }

        //解锁
        redisLock.unLock(productId, String.valueOf(value));


    }
}
